<template>
    <div>
        <!-- 面包屑导航区域 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/admin' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>用户管理</el-breadcrumb-item>
            <el-breadcrumb-item>用户列表</el-breadcrumb-item>
        </el-breadcrumb>

        <!-- 卡片视图区域 -->
        <el-card>
            <el-row :gutter="20">
                <el-col :span="8">
                    <!-- 搜索与添加区域 -->
                    <el-input placeholder="请输入搜索内容"
                    v-model="queryInfo.userName" clearable @clear="getUserList">
                        <el-button slot="append" icon="el-icon-search"
                        @click="getUserList"></el-button>
                    </el-input>
                </el-col>
                <el-col :span="4">
                    <el-button type="primary" @click="addDialogVisible = true">添加管理员</el-button>
                </el-col>
            </el-row>

            <!-- 用户列表区域 -->
            <el-table :data="userList" stripe>
                <el-table-column type="index" label="序号" width="80"></el-table-column>
                <el-table-column prop="userName" label="用户名" width="120"></el-table-column>
                <el-table-column prop="nickname" label="昵称" width="120"></el-table-column>
                <!-- <el-table-column prop="headImg" label="头像" width="160"></el-table-column> -->
                <el-table-column label="用户类型" width="120">
                    <template slot-scope="scope">
                        <el-tag :type="scope.row.userType.userTypeName.includes('管理员')? '':'info'">{{ scope.row.userType.userTypeName }}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="是否锁定" width="180">
                    <template slot-scope="scope">
                        
                        <el-switch active-text="锁定" inactive-text="解锁" v-model="scope.row.isLock" @change="userStateChanged(scope.row)"></el-switch>
                        
                    </template>
                </el-table-column>
                <el-table-column prop="phone" label="手机号" width="180"></el-table-column>
                <el-table-column prop="email" label="邮箱" width="180"></el-table-column>
                <el-table-column prop="createTime" label="创建时间" width="180"></el-table-column>
                <el-table-column prop="updateTime" label="更新时间" width="180"></el-table-column>
                <el-table-column label="操作" fixed="right" width="180">
                    <template slot-scope="scope">
                        <el-tooltip effect="dark" content="修改" placement="top" :enterable="false">
                            <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row)"></el-button>
                        </el-tooltip>
                        <el-tooltip effect="dark" content="删除" placement="top" :enterable="false">
                            <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeUserByUserId(scope.row.userId)"></el-button>
                        </el-tooltip>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页区域 -->
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="queryInfo.currentPage"
                :page-sizes="[1, 5, 10, 20, 30]" :page-size="queryInfo.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total">
            </el-pagination>
        </el-card>
        <!-- 添加用户的对话框 -->
        <el-dialog title="添加管理员" :visible.sync="addDialogVisible" width="50%" @close="addDialogClosed">
            <!-- 内容主体区域 -->
            <el-form :model="addForm" :rules="formRules" ref="addFormRef" label-width="70px">
                <el-form-item label="用户名" prop="userName">
                    <el-input v-model="addForm.userName"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input v-model="addForm.password" show-password></el-input>
                </el-form-item>
                <el-form-item label="昵称" prop="nickname">
                    <el-input v-model="addForm.nickname"></el-input>
                </el-form-item>
                <el-form-item label="手机号" prop="phone">
                    <el-input v-model="addForm.phone"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="addForm.email"></el-input>
                </el-form-item>
            </el-form>
            <!-- 底部区域 -->
            <span slot="footer" class="dialog-footer">
                <el-button @click="addDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="addUser">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 修改用户的对话框 -->
        <el-dialog title="修改用户" :visible.sync="editDialogVisible" width="50%" @close="editDialogClosed">
            <!-- 内容主体区域 -->
            <el-form :model="editForm" :rules="formRules" ref="editFormRef" label-width="70px">
                <el-form-item label="用户名" prop="userName">
                    <el-input v-model="editForm.userName" disabled></el-input>
                </el-form-item>
                <!-- <el-form-item label="密码" prop="password">
                    <el-input v-model="editForm.password"></el-input>
                </el-form-item> -->
                <el-form-item label="昵称" prop="nickname">
                    <el-input v-model="editForm.nickname"></el-input>
                </el-form-item>
                <el-form-item label="手机号" prop="phone">
                    <el-input v-model="editForm.phone"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="editForm.email"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="editUser">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>
<script>

export default {
    data() {
        //验证手机号的规则
        var checkPhone = (rule, value, callback) => {
            //验证手机号的正则表达式
            const regPhone = /^(0|86|17951)?(13[0-9]|15[0123456789]|17[678]|18[0-9]|14[57])[0-9]{8}$/;
            if(regPhone.test(value)){
                //合法手机号
                return callback();
            }
            callback(new Error('请输入合法的手机号'));
        }
        //验证邮箱的规则
        var checkEmail = (rule, value, callback) => {
            //验证邮箱的正则表达式
            const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/;
            if(regEmail.test(value)){
                //合法邮箱
                return callback();
            }
            callback(new Error('请输入合法的邮箱'))
        }
        return {
            // 获取用户列表的参数对象
            queryInfo: {
                userName: '',
                //当前页数
                currentPage: 1,
                //当前每页显示多少条数据
                pageSize: 10
            },
            userList: [],
            total: 0,
            //控制添加用户对话框的显示与隐藏
            addDialogVisible: false,
            //添加用户的表单数据
            addForm: {
                userName: '',
                password: '',
                nickname: '',
                phone: '',
                email: '',
                userType: {
                    userTypeId: 1
                }
            },
            //表单的验证规则对象
            formRules: {
                userName: [
                    { required: true, message: '请输入用户名', trigger: 'blur' },
                    { min: 5, max: 15, message: '用户名的长度在5-15个字符之间', trigger:'blur' }
                ],
                password: [
                    { required: true, message: '请输入密码', trigger: 'blur' },
                    { min: 5, max: 15, message: '密码的长度在5-15个字符之间', trigger:'blur' }
                ],
                nickname: [
                    { required: true, message: '请输入昵称', trigger: 'blur' },
                    { min: 3, max: 8, message: '昵称的长度在5-15个字符之间', trigger:'blur' }
                ],
                phone: [
                    { required: true, message: '请输入手机号', trigger: 'blur' },
                    { validator: checkPhone, trigger: 'blur' }
                ],
                email: [
                    { required: true, message: '请输入邮箱', trigger: 'blur' },
                    { validator: checkEmail, trigger: 'blur' }
                ]
            },
            // 控制修改用户对话框的显示和隐藏
            editDialogVisible: false,
            // 修改用户的表单数据
            editForm: {}
        }
    },
    computed:{
        
    },
    created() {
        this.getUserList();
    },
    methods: {
        getUserList() {
            this.$axios
            .get('/user', { params: this.queryInfo })
            .then(res => {
                const data = res.data;
                if(data.code !== '001') return this.$notifyError("数据获取异常");
                this.userList = data.list;
                this.total = data.totalRecords;
            })
            .catch(err => {
                console.log(err);
            });
        },
        //监听pagesize改变的事件
        handleSizeChange(newSize){
            this.queryInfo.pageSize = newSize;
            this.getUserList();
        },
        //监听 页码值 改变的事件
        handleCurrentChange(newPage){
            this.queryInfo.currentPage = newPage;
            this.getUserList();
        },
        //监听switch开关状态的改变
        userStateChanged(user){
            this.$axios
            .put(`user/${user.userId}/state/${user.isLock}`)
            .then(res => {
                const data = res.data;
                if(data.code !== '001'){
                    //失败后撤回页面按钮的状态
                    user.isLock = !user.isLock;
                    return this.$notifyError(data.msg);
                }
                this.$notifySucceed(data.msg);
            })
            .catch(err => {
                console.log(err);
            });
        },
        //监听添加用户对话框的关闭事件
        addDialogClosed(){
            this.$refs.addFormRef.resetFields();
        },
        //添加用户
        addUser(){
            this.$refs.addFormRef.validate(valid => {
                if (!valid) return;
                //发起添加请求
                this.$axios
                .post('/user', this.addForm)
                .then(res => {
                    const data = res.data;
                    if(data.code !== '001'){
                        return this.$notifyError(data.msg);
                    }
                    this.$notifySucceed(data.msg);
                    //隐藏对话框
                    this.addDialogVisible = false;
                    //重新获取用户列表数据
                    this.getUserList();
                })
                .catch(err => {
                    console.log(err);
                });
            });
        },
        //展示编辑用户的对话框
        showEditDialog(user){
            this.editForm = user;
            this.editDialogVisible = true;

        },
        // 监听修改用户对话框的关闭事件
        editDialogClosed(){
            this.$refs.editFormRef.resetFields();
        },
        //修改用户
        editUser(){
            this.$refs.editFormRef.validate(valid => {
                if(!valid) return;
                this.$axios
                .put('/user', this.editForm)
                .then(res => {
                    const data = res.data;
                    if(data.code !== '001'){
                        return this.$notifyError(data.msg);
                    }
                    //关闭对话框
                    this.editDialogVisible = false;
                    //刷新数据列表
                    this.getUserList();
                    //提示修改成功
                    this.$notifySucceed(data.msg);
                })
                .catch(err => {
                    console.log(err);
                });
            });
        },
        //根据id删除用户信息
        removeUserByUserId(userId){
            //弹框询问是否删除数据
            this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                //发起删除用户请求
                this.$axios
                .delete('/user/' + userId)
                .then(res => {
                    const data = res.data;
                    if(data.code !== '001'){
                        return this.$notifyError(data.msg);
                    }
                    this.$notifySucceed(data.msg);
                    this.getUserList();
                    
                })
                .catch(err => {
                    console.log(err);
                })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        }
    }
}
</script>

<style lang="less" scoped>

</style>